package server;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import utils.ClientServerMessage;
import utils.PrintMsg;

import broadcast.Broadcast;
import broadcast.BroadcastListener;

import common.Message;

public class ServerUDPTimeoutListner implements Runnable, BroadcastListener {
	private final long timeoutMillsDelay = 10000;
	private Broadcast groupBc;
	private Broadcast globalBc;

	public ServerUDPTimeoutListner() {
		groupBc = new Broadcast(this, null, 10000, 10001, 10002); // second arg
																	// is a set
																	// of
	}

	@Override
	public void run() 
	{
		while(true)
		{
			try {
			Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			synchronized(ServerUDPSend.UDPACKBuffer)
			{
				while (ServerUDPSend.UDPACKBuffer.size() > 0)
				{
					long timeoutMills = System.currentTimeMillis();
					Iterator<Entry<Long, Message>> it = ServerUDPSend.UDPACKBuffer.entrySet().iterator();
					while(it.hasNext())
					{
						Map.Entry pairs = (Map.Entry)it.next();
						if(((Message)pairs.getValue()).getSentTime() + timeoutMillsDelay < timeoutMills)
						{
							/*timed out..do something*/
							PrintMsg.PrintStatic("Timed out..", "Checksum: "+ pairs.getKey()+ "\n");

							Message m = (Message)pairs.getValue();
							//m.setSource(source)
							groupBc.broadcast(m);
							ServerUDPSend.UDPACKBuffer.remove(pairs.getKey());
							
							break;
						}
					}
				}
			}
		}
		
	}

	@Override
	public void onDelivery(Message m) {

		String msg = new String(m.getData(), 0, m.getData().length);
		ClientServerMessage csm = new ClientServerMessage(msg);
		RelayMessages.getInstance().SendMessage(-1, csm.getClientId(),
				csm.getMessage());
	}

}
